#include <event2/event.h>
#include <event2/listener.h>
#include <iostream>
#include <signal.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace std;

static const char *ip = "192.168.232.128";
static const int port = 12345;
const int BUFFER_SIZE = 5;

static void read_cb(evutil_socket_t sockfd, short event_type, void *args) {
    event *ev = (event*)args;
    char buffer[BUFFER_SIZE] = {0};
    if (event_type & EV_TIMEOUT) {
        cout << "Time out" << endl;
        event_free(ev);
        evutil_closesocket(sockfd);
        return;
    }
    int len = recv(sockfd, buffer, BUFFER_SIZE - 1, 0);
    if (len > 0) {
        // cout << buffer << flush;
        for (int i = 0; i < 4; i++) {
            if (buffer[i] == '\r')  cout << "\\r";
            else if (buffer[i] == '\n') cout << "\\n";
            else cout << buffer[i];
        }cout << endl;
        send(sockfd, "okk\n", 4, 0);
    } else {
        cout << "event_free" << endl;
        event_free(ev);
        evutil_closesocket(sockfd); // 记得避免重复关闭，否则报错 [warn] Epoll ADD(1) on fd 7 failed.
    }
}

static void listen_cb(evutil_socket_t sockfd, short event_type, void *args) {
    cout << "listen the connection" << endl;
    sockaddr_in addr;
    socklen_t size = sizeof(addr);
    evutil_socket_t clientfd = accept(sockfd, (sockaddr*)&addr, &size);
    char cli_ip[16] = {0};
    evutil_inet_ntop(AF_INET, &addr.sin_addr, cli_ip, sizeof(cli_ip) - 1);
    cout << "client IP: " << cli_ip << endl;

    event_base *base = (event_base*)args;
    event *read_ev = event_new(base, clientfd, EV_READ | EV_PERSIST | EV_ET, read_cb, event_self_cbarg());  // 开边沿触发后记得想办法一次把缓冲区数据读取完，要不就会读到之前发送的数据
    timeval t {3, 0};
    event_add(read_ev, &t);
}

int main() {
    event_base *base = event_base_new();

    evutil_socket_t sockfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(sockfd > 0);

    // 设置非阻塞和地址重用
    evutil_make_socket_nonblocking(sockfd);
    evutil_make_listen_socket_reuseable(sockfd);


    sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    inet_pton(AF_INET, ip, &address.sin_addr);
    int ret = ::bind(sockfd, (sockaddr*)&address, sizeof(address));
    assert(ret == 0);

    listen(sockfd, 10);
    event *ev = event_new(base, sockfd, EV_PERSIST | EV_READ, listen_cb, base);
    event_add(ev, 0);

    

    // 进入事件主循环
    event_base_dispatch(base);  // 相当于 event_base_loop(base, 0);
    event_free(ev);
    event_base_free(base);
    // 添加 ctrlC 事件后先挂起再杀进程 pkill -9 a.out

}